from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from app.config import settings

# MySQL 8.x 连接参数配置
connect_args = {
    "charset": "utf8mb4",
    "connect_timeout": 10,
}

# 构建数据库引擎
# pool_pre_ping: 每次连接前检查连接是否有效
# pool_recycle: 连接回收时间（秒），防止 MySQL 超时断开
# echo: 是否打印 SQL 语句（生产环境建议关闭）
engine = create_engine(
    settings.DATABASE_URL,
    pool_pre_ping=True,
    pool_recycle=3600,
    pool_size=10,
    max_overflow=20,
    echo=False,
    connect_args=connect_args
)

SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()


def get_db():
    """数据库会话依赖"""
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

